package org.lboot.rbac.config;

import cn.dev33.satoken.stp.StpInterface;
import org.lboot.rbac.module.role.SysRole;
import org.lboot.rbac.module.user.SysUser;
import org.lboot.rbac.module.user.SysUserService;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author kindear
 * 基于 SaToken的实现
 */
@Slf4j
@Component
@AllArgsConstructor
public class SaAuthConfig implements StpInterface {
    SysUserService userService;

    @Override
    public List<String> getPermissionList(Object o, String s) {
        Long userId = Long.parseLong(o.toString());
        Optional<SysUser> userOp = userService.getOne(userId);
        if(!userOp.isPresent()){
            return new ArrayList<>();
        }
        SysUser user = userOp.get();
        Set<SysRole> roles = new HashSet<>(userService.getRoles(user.getId()));
        List<String> perms = new ArrayList<>();
        for (SysRole role:roles){
            if (role.getStatus().equals(1)){
                perms.addAll(role.getPermissions());
            }
        }
        // 去重
        return perms.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public List<String> getRoleList(Object o, String s) {
        Long userId = Long.parseLong(o.toString());
        Optional<SysUser> userOp = userService.getOne(userId);
        if(!userOp.isPresent()){
            return new ArrayList<>();
        }
        SysUser user = userOp.get();
        Set<SysRole> roles = new HashSet<>(userService.getRoles(user.getId()));
        List<String> roleKeys = new ArrayList<>();
        for (SysRole role:roles){
            // 禁用状态下角色失效
            if (role.getStatus().equals(1)){
                roleKeys.add(role.getRoleKey());
            }

        }
        return roleKeys.stream().distinct().collect(Collectors.toList());
    }
}
